package org.yyj.dao.impl;

import org.yyj.dao.ZyDao;
import org.yyj.factory.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.yyj.model.Zyb;

import java.util.List;

public class ZyDaoImp implements ZyDao {
    @Override
    //实现getOneZy方法 查询某个专业信息
    public Zyb getOneZy(Integer zyId) {
        try{
            /*//创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();*/
            Session session= HibernateSessionFactory.getSession();
            //开启事务
            Transaction transaction=session.beginTransaction();
            Query query=session.createQuery("from Zyb where id=?");
            query.setParameter(0,zyId);
            query.setMaxResults(1);
            Zyb zyb=(Zyb) query.uniqueResult();
            transaction.commit();
            session.close();
            return zyb;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @Override
    //实现getAll方法
    public List getAll() {
        try {
            //创建Configuration
            Configuration configuration=new
                    Configuration().configure("hibernate.cfg.xml");
            //获取SessionFactory
            SessionFactory sessionFactory=configuration.buildSessionFactory();
            //获取Session
            Session session=sessionFactory.openSession();
            /*Session session= HibernateFactory.getSession();*/
            //开启事务
            Transaction transaction=session.beginTransaction();
            List list=session.createQuery("from Zyb ").list();
            transaction.commit();
            session.close();
            return list;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
